package jhc.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.dbutils.QueryRunner;

import jhc.cn.db.UserDao;
import jhc.cn.AirSpace;

/**
 * Servlet implementation class CheckData
 */
@WebServlet("/check.do")
public class CheckData extends HttpServlet {
	private static final long serialVersionUID = 1L;
       


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String vcode = request.getParameter("vcode");
		response.setContentType("application/json; charset=utf8");
		PrintWriter out = response.getWriter();
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(AirSpace.KET_QUERY_RUNNER);
		boolean isExists = false;
		try {
			isExists = UserDao.exists(runner, username);
		} catch (SQLException e) {
			// TODO: handle exception
		}
		if(isExists) {
			out.println("{\"ok\": 1}");
		}else {
			out.println("{\"ok\": 0}");
		}
		
		

//		String expected = (String)request.getSession().getAttribute(AirSpace.VCODE_KEY);
//		if(!vcode.equals(expected)) {
//			out.println("{\"ok\": -2}");
//		}else {
//			out.println("{\"ok\": 2}");
//		}
	}

	private String getContent(Part part) throws IOException {
		try(Scanner scanner = new Scanner(part.getInputStream())) {
			return scanner.next();
		}
	}
}
